package com.terracloud.server.controller;

import com.terracloud.server.common.data.Menu;
import com.terracloud.server.common.data.exception.ThingsboardException;
import com.terracloud.server.common.data.tree.TreeUtil;
import com.terracloud.server.dao.model.sql.MenuEntity;
import com.terracloud.server.dao.sql.menu.MenuRepository;
import com.terracloud.server.dao.sql.role.RoleRepository;
import com.terracloud.server.dao.sql.role.UserRoleRepository;
import com.terracloud.server.service.entitiy.role.RoleService;
import com.terracloud.server.service.security.model.SecurityUser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

/**
 *
 * @author chenhainan
 * @since 2025/10/17
 */
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
@Slf4j
public class MenuController extends BaseController {

    private final MenuRepository menuRepository;

    private final UserRoleRepository userRoleRepository;

    private final RoleService roleService;

    @GetMapping("/menu/tree")
    @PreAuthorize("hasAnyAuthority('TENANT_ADMIN')")
    public List<Menu> menuTree() {
        final var menus = menuRepository.findAll().stream().map(MenuEntity::toData)
                .filter(menu -> RoleService.TENANT_ADMIN_MENUS.contains(menu.getName()))
                .toList();
        return TreeUtil.buildTree(menus);
    }

    @GetMapping("/menu/current")
    @PreAuthorize("hasAnyAuthority('TENANT_ADMIN','SYS_ADMIN')")
    public Set<String> menus() throws Throwable {
        final var user = getCurrentUser();
        return roleService.findUserRole(user.getUuidId()).getMenus();
    }


}
